package com.app.samba;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.app.samba.util.AppUtil;
import com.app.samba.util.FileUtils;
import com.app.samba.util.RealPathFromUriUtils;
import com.app.samba.util.SambaUtil;
import com.app.samba.util.ToastUtil;

import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import jcifs.UniAddress;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbSession;

import static com.app.samba.DebugLog.SAMBA_LOG;

/**
 * Created Date 2019/6/17
 *
 * @author liangkun
 * description：需要samba权限的name 和密码
 */
public class RequestNameActivtiy extends AppCompatActivity {
    private Button btnOne;
    private Button btnTwo;
    private Button btnThree;
    private String path; //路径
    String host = "192.168.31.76"; //samba--ip 本地电脑的
    String filePath = "/图片电影音乐素材/pic/CK1A3133.JPG"; //单个文件下载
    // 单个文件下载
    public static SimpleDateFormat sdf = new SimpleDateFormat("HHmmssSSS", Locale.CHINA);
    String uploadPath = "/图片电影音乐素材/upload/"; //上传samba服务器的文件夹
    String listPath = "/图片电影音乐素材/电影/"; //上传samba服务器的文件夹
    private static final int REQUEST_PICK_IMAGE = 10086;
    private String realPathFromUri;
    private ImageView ivShow;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_req);
        btnOne = findViewById(R.id.btn_one);
        btnTwo = findViewById(R.id.btn_two);
        btnThree = findViewById(R.id.btn_three);
        ivShow = findViewById(R.id.iv_iamge);
        path = FileUtils.ROOT_PATH + AppUtil.getPackageName(RequestNameActivtiy.this) + FileUtils.HEAD_PATH;

        btnOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //有权限下载
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        downLoadRequest(host, filePath, path);
                    }
                }).start();


            }
        });
        btnTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getImage();
            }
        });
        btnThree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //有权限上传
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String remoutUrl = "smb://" + host + uploadPath;
                        uploadRequest(remoutUrl, realPathFromUri);
                    }
                }).start();

            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                showListFile();
            }
        }).start();

    }

    /**
     * 显示文件
     */
    private void showListFile() {
        String username = "administrator";
        String password = "065021";
        try {
            List<Map<String, Object>> maps = SambaUtil.sambaFileListInfo(username, password, host, listPath);
            for (int i = 0; i < maps.size(); i++) {
                Object o = maps.get(i).get("name");
                DebugLog.d(SAMBA_LOG+"名字 "+maps.get(i).get("name")+" 路径 "+maps.get(i).get("path"));
            }
        } catch (MalformedURLException | SmbException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_PICK_IMAGE:
                    if (data != null) {
                        realPathFromUri = RealPathFromUriUtils.getRealPathFromUri(this, data.getData());
//                        fileName = realPathFromUri.substring(realPathFromUri.lastIndexOf("/") + 1, realPathFromUri.length());
                        showImage(realPathFromUri);
                        DebugLog.d(SAMBA_LOG + " realPathFromUri " + realPathFromUri);

                    } else {
                        ToastUtil.toastLongContent(this, "图片损坏，请重新选择");
                    }

                    break;
            }
        }
    }

    /**
     * 下载文件
     *
     * @param host        samba主机
     * @param remoutSorce samba下载资源文件夹
     * @param path        下载到手机目录
     */
    private void downLoadRequest(String host, String remoutSorce, String path) {
        DebugLog.d(SAMBA_LOG + "进入 downLoadRequest() ...." + " remoteUrl " + remoutSorce + " path " + path);
        String username = "administrator";
        String password = "065021";
        try {
            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(host, username, password);
            UniAddress ua = UniAddress.getByName(host);
            SmbSession.logon(ua, auth);//验证是否能够成功登录
//          //创建Smb文件,地址一定要使用smb://
            SmbFile remoteSmbFile = new SmbFile("smb://" + host + filePath, auth);
            SambaUtil.downloadFileFromSamba(remoteSmbFile, path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载文件
     *
     * @param remoutUrl samba URL
     * @param path      上传文件的路径资源
     */
    private void uploadRequest(String remoutUrl, String path) {
        DebugLog.d(SAMBA_LOG + "进入 downLoadRequest() ...." + " remoteUrl " + remoutUrl + " path " + path);
        String username = "administrator";
        String password = "065021";
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(host, username, password);
        try {
            SambaUtil.uploadFileToSamba(remoutUrl, auth, path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //加载图片
    private void showImage(String imaePath) {
        Bitmap bm = BitmapFactory.decodeFile(imaePath);
        ivShow.setImageBitmap(bm);

    }

    /**
     * 获取图片
     */
    @SuppressLint("ObsoleteSdkInt")
    private void getImage() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"),
                    REQUEST_PICK_IMAGE);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_PICK_IMAGE);
        }
    }
}
